<template>
  <h3>题目管理</h3>
  <!-- 表单-->
  <div class="topic-form">
    <div class="form">
      <div class="opt">
        <span class="label">考试分类:</span>
        <el-select
          @change="chooseCategoryFn"
          v-model="form.id"
          placeholder="选择分类"
          style="width: 640px"
          size="large"
        >
          <el-option
            v-for="item in categories"
            :key="item.xid"
            :label="item.text"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="opt">
        <span class="label">试卷名称:</span>
        <el-select
          @change="chooseExamFn"
          v-model="form.eid"
          placeholder="选择试卷"
          style="width: 640px"
          size="large"
        >
          <el-option
            v-for="item in result"
            :key="item.yid"
            :label="item.name"
            :value="item.eid"
          />
        </el-select>
      </div>
      <div class="opt">
        <span class="label">题目:</span>
        <el-input
          v-model="form.question"
          style="width: 640px"
          placeholder="请输入题目"
          size="large"
        />
      </div>
      <div class="opt">
        <span class="label top">选项:</span>
        <!-- 题目的选项 -->
        <ul>
          <li v-for="(item, i) in arr">
            <input
              @input="save"
              class="op"
              v-model="item.op"
              type="text"
              placeholder=""
              maxlength="1"
            />
            <input
              @input="save"
              class="ov"
              v-model="item.ov"
              type="text"
              placeholder="请输入选项"
            />
            <el-icon size="large" @click="remove(i)">
              <Remove />
            </el-icon>
          </li>
          <li>
            <button class="btn" @click="add">增加题目选项</button>
          </li>
        </ul>
      </div>

      <div class="opt">
        <span class="label">答案:</span>
        <el-input
          v-model="form.answer"
          style="width: 640px"
          placeholder="请输入答案"
          size="large"
        />
      </div>
      <div class="opt">
        <span class="label">分值:</span>
        <el-input
          v-model="form.score"
          style="width: 640px"
          placeholder="分值"
          size="large"
        />
      </div>

      <div class="opt">
        <span class="label">数量信息:</span>
        【
        <span> {{ examInfo.num }}</span> /
        <span> {{ count }}</span>
        】
      </div>

      <div class="opt">
        <el-button @click="submitTopicFn" type="primary" size="large"
          >提交题目</el-button
        >
        <el-button @click="resetTopicFn" type="warning" plain size="large"
          >重置</el-button
        >
      </div>
    </div>
  </div>
  <!-- 表格（列表） -->
  <div class="topic-list"></div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { categoryList, examList } from '../../api/request'
import api from '../../api/http'
import { ElMessage } from 'element-plus'

interface Item {
  id?: string
  eid: string
  name: string
  question: string
  answer: string
  score: number | string
  option?: string
}

let form = reactive<Item>({
  eid: '',
  name: '',
  question: '',
  answer: '',
  score: 0,
  id: '',
  option: '',
})

let categories = ref<any>([])

let exams = ref<any>([])

let result = ref<any>([])

let examInfo = ref<any>({
  num: 0,
})

let count = ref<number>(0)

let arr = ref<any>([
  {
    op: 'A',
    ov: '',
  },
  {
    op: 'B',
    ov: '',
  },
])
let n = arr.value.length - 1
const add = () => {
  n++
  if (n < 4) {
    arr.value.push({
      op: '',
      ov: '',
    })
  }
  n = n == 4 ? 4 : n
}
const remove = (index: number) => {
  n--
  if (n >= 0) {
    n = 0
  }
  arr.value.splice(index, 1)
}
const save = () => {
  let data = arr.value
  if (data && data.length != 0) {
    let newArr = []
    for (let i = 0; i < data.length; i++) {
      let obj: any = {}
      obj['key'] = data[i].op
      obj['value'] = data[i].ov

      newArr.push(obj)
    }
    console.log(newArr)
    let str = newArr && JSON.stringify(newArr)
    console.log(str)
    form.option = str
  }
}

const chooseCategoryFn = (value: string) => {
  let arr5 = exams.value.filter((item: any) => {
    return item.id == value
  })
  result.value = arr5

  form.eid = ''
}
const chooseExamFn = async (value: string) => {
  console.log('eid:', value)

  let arr6 = result.value.filter((item: any) => {
    return item.eid == value
  })
  if (arr6.length == 1) {
    examInfo.value = arr6[0]

    form.score = arr6[0].score

    form.name = arr6[0].name
  }
  if (value) {
    await api.topicNum({ eid: value }).then(
      content => {
        console.log(content)
        let { code, result } = content
        if (code == 200) {
          count.value = result[0].total
        }
      },
      err => {
        console.log(err)
      },
    )
  }
}

const resetTopicFn = async () => {
  form.eid = ''
  form.name = ''
  form.question = ''
  form.answer = ''
  form.score = 0
  form.option = ''
  form.id = ''

  arr.value = [
    {
      op: 'A',
      ov: '',
    },
    {
      op: 'B',
      ov: '',
    },
  ]
}
const submitTopicFn = async () => {
  let { eid, name, question, answer, score, option } = form
  if (eid && name && question && answer && score && option) {
    api.topicAdd({ eid, name, question, answer, score, option }).then(
      content => {
        let { code, msg } = content
        if (code == 200) {
          resetTopicFn()
          ElMessage.success(msg)
        } else {
          ElMessage.error(msg)
        }
      },
      err => {
        console.log(err)
      },
    )
  } else {
    ElMessage.error('缺少参数，请重新提交')
  }
}
// 获取试卷列表
const examListFn = async () => {
  await examList().then(content => {
    let { code, msg, result } = content
    if (code == 200) {
      let arr = result.map((item: any, i: number) => {
        item.yid = i + 1
        return item
      })
      exams.value = arr
    } else {
      ElMessage.error(msg)
    }
  })
}
// 获取分类列表
const getCategoryListFn = async () => {
  await categoryList().then(content => {
    let { code, result } = content
    if (code == 200) {
      let arr = result.map((item: any) => {
        item.xid = Math.random().toString().slice(2)
        return item
      })
      categories.value = arr
    }
  })
}
// 初始化
examListFn()
getCategoryListFn()
</script>

<style lang="scss">
.topic-form {
  .opt {
    margin-top: 15px;
    width: 100%;
    display: flex;
    align-items: center;

    .label {
      display: inline-block;
      width: 90px;
      text-align: right;
      padding: 0 10px;

      &.top {
        align-self: flex-start;
      }
    }

    ul {
      li {
        margin-bottom: 10px;

        .op {
          width: 40px;
          height: 40px;
          text-align: center;
          border: 1px solid #ccc;
        }

        .ov {
          width: 588px;
          height: 40px;
          margin-left: 10px;
          padding-left: 10px;
        }

        .btn {
          background: skyblue;
          padding: 8px 15px;
          color: #fff;
          cursor: pointer;
          border-radius: 5px;
        }

        .btn2 {
          margin-left: 10px;
          background-color: deepskyblue;
        }
      }
    }
  }

  .el-icon {
    font-size: 20px !important;
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>
